<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // f(i 代表的第i个元素结尾的连续数组最大的和)
      // max{ f(i)} [-2,1,-3,4,-1,2,1,-5,4]
      // f(i) = max(f(i-1)+nums[i],nums[i])
      function maxSubArray(nums) {
        let pre = nums[0]
        let max = nums[0]
        for (let i = 1; i < nums.length; i++) {
          pre = Math.max(pre + nums[i], nums[i])
          max = Math.max(pre, max)
        }
        return max
      }
      console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
      console.log(maxSubArray([1]))
      console.log(maxSubArray([5, 4, -1, 7, 8]))
    </script>
  </body>
</html>
